<template>
	<view style="padding:10px">
		<view>
			<u-form>
				<u-form-item label="日期:"  border-bottom="false" label-width="150" >
					<u-input v-model="formData.time" disabled="true" border="true"  />
				</u-form-item>
			</u-form>
			
			<map id="aqffMap" ref="aqffMap" class="map" 
			:latitude="formData.lat" 
			:longitude="formData.lng" 
			:markers="covers"
			:circles="circles"
			:show-location="true"
			>
				<!-- <cover-image class="control" src="/static/map/location-fill.png" @click="controlclick">
					
				</cover-image> -->
			</map>
			<view v-if="clockPorintName.length>0">签到点：{{clockPorintName}}</view>
			<view v-if="clockPointTime">签到时间：{{clockPointTime}}</view>
			<view v-if="clockPointLength">距离打卡点：{{clockPointLength}}米</view>
			<view class="buttons">
				<u-button  @click="clockIn()" :disabled="submitBtn" type="primary">{{btnName}}</u-button>
					<u-button  @click="toQueryPage"  type="success">签到查询</u-button>
				</view>
			</view>
			
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import { mapState} from 'vuex';
	
	var appMap = null;
	export default {
		name:"xlqd",
		computed:mapState(['user', ]),
		data() {
			return{
				mapTimer:'',
				dateTimer:'',
				btnName:'巡逻签到',
				submitBtn:false,
				aqffMap:null,
				formData:{
					time: this.$util.getNowDT(),
					userId: '',
					location: '',
					lat: '',
					lng: '',
				},
				covers:[],
				points:[],
				circles:[],
				clockPorintName:[],
				clockPointTime:'',
				clockPointLength:''
			}
		},
		methods:{
			toQueryPage(){
				//this.submitBtn = true;
				this.$u.route('/pages/views/xlqdquery');
			},
			initClockPoint(){
				this.$http.post('/aqff/getClockPointForUser',this.user.user).then(res=>{
					let data = res.data.data;
					this.clockPorintName = [];
					this.covers = [];
					this.circles = [];
					this.points = [];
					if(data&&data.length>0){
						//this.points = data;
						for(let point of data){
							let {id,lat,lng,radius,name} = {...point};
							var lnglat = this.$coord.wgs84togcj02(lng,lat);
							if(lnglat&&lnglat.length>0){
								lng = lnglat[0];
								lat = lnglat[1];
							}
							point.lat = lat;
							point.lng = lng;
							this.points.push(point);
							let circle = {
								latitude: lat,
								longitude: lng,
								radius:radius,
								fillColor: '#ff000080'
							}
							let mark = {
								id:id,
								latitude :lat,
								longitude : lng,
								iconPath : '/static/icon/0006.png',
							}
							this.clockPorintName.push(name);
							this.covers.push(mark);
							this.circles.push(circle);
						}
					}
				}).catch(err=>{
					
				})
				/* let clockPoints = this.user.user.clockPoint;
				if(clockPoints){
					this.points = clockPoints;
					for(let point of clockPoints){
						let {id,lat,lng,radius,name} = {...point};
						let circle = {
							latitude: lat,
							longitude: lng,
							radius:radius,
							fillColor: '#ff000080'
						}
						let mark = {
							id:id,
							latitude :lat,
							longitude : lng,
							iconPath : '/static/icon/0006.png',
						}
						this.clockPorintName.push(name);
						this.covers.push(mark);
						this.circles.push(circle);
					}
				} */
			},
			clockIn(){
				this.submitBtn = true;
				this.formData.userId = this.user.user.id || '';
				const that = this;
				if(!this.formData.lat||!this.formData.lng||!this.formData.location){
					this.$refs.uToast.show({
						title: '位置信息获取失败！',
						type: 'error'
					})
					return;
				}
				if(!this.clockValidate(this.formData.lat,this.formData.lng)){
					this.$http.post("/aqff/clockIn",this.formData).then(res => {
						let data = res.data.data;
						if(data){
							that.$refs.uToast.show({
								title: '签到成功',
								type: 'success',
								// callback: ()=>{
								// 	that.$u.route({
								// 		type:'back',
								// 		delta: 1
								// 	})
								// }
								//back: true
							})
						}else{
							this.submitBtn = false;
							this.$refs.uToast.show({
								title: '签到异常,请稍后重试',
								type: 'error'
							})
						}
					}).catch(err => {
						this.submitBtn = false;
						this.$refs.uToast.show({
							title: '提交失败！',
							type: 'error'
						}) 
					})
				}else{
					this.submitBtn = false;
					//this.loading = false;
					this.$refs.uToast.show({
						title: this.clockValidate(this.formData.lat,this.formData.lng),
						type: 'error'
					})
				}
				
			},
			getRad(d){
				let PI = Math.PI;
			    return d*PI/180.0;
			},
			getFlatternDistance(lat1,lng1,lat2,lng2){
				let lat = (lat1 + lat2)/2;
				let lng = (lat1 - lat2)/2;
				let z = (lng1 - lng2)/2;
				var f = this.getRad(lat);
				var g = this.getRad(lng);
				var l = this.getRad(z);
				
				var sg = Math.sin(g);
				var sl = Math.sin(l);
				var sf = Math.sin(f);
				
				var s,c,w,r,d,h1,h2;
				var a = 6378137.0;
				var fl = 1/298.257;
				
				sg = sg*sg;
				sl = sl*sl;
				sf = sf*sf;
				
				s = sg*(1-sl) + (1-sf)*sl;
				c = (1-sg)*(1-sl) + sf*sl;
				
				w = Math.atan(Math.sqrt(s/c));
				r = Math.sqrt(s*c)/w;
				d = 2*w*a;
				h1 = (3*r -1)/2/c;
				h2 = (3*r +1)/2/s;
				
				return d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg));
			},
			clockValidate(currX,currY){
				let validMsg = null;
				if(this.points&&this.points.length>0){
					//2020-08-22 10:12:25
					let time = this.formData.time.substr(11,5);
					let {lat,lng,clockStartTime,clockEndTime,radius} = {...this.points[0]};
					//当前位置距打卡点距离
					let distance = this.getFlatternDistance(parseFloat(currX),parseFloat(currY),parseFloat(lat),parseFloat(lng));
					this.clockPointLength = Math.round(distance);
					this.clockPointTime=clockStartTime+" - "+clockEndTime;
					
					if(distance>radius)
						return validMsg = "尚未到达签到点";
					
					if(time&&clockStartTime&&clockEndTime){
						if(!this.$util.compareBetweenTime(clockStartTime,time,clockEndTime))
							return validMsg = "请在设定时段内打卡";
						else 
							return false;
					}
					else
						return validMsg = "未设置打卡时间"
				}else{
					return false;
					// return validMsg = "未设置打卡时间或位置";
				}
			},
			controlclick(e){
				let obj  = {
					latitude:this.formData.lat,
					longitude:this.formData.lng
				}
				this.aqffMap.moveToLocation(obj);
				//uni.openLocation(obj);
			},
			setLoaction(){
				let locations = this.$auth.getLocationInfo();
				console.log('locations......');
				console.log(locations);
				this.formData.lat = locations.lat;
				this.formData.lng = locations.lng;
				this.formData.location = locations.address;
				this.initClockPoint();
			},
			dateInterval(){
				this.formData.time = this.$util.getNowDT();
				if(this.clockValidate(this.formData.lat,this.formData.lng)){
					this.submitBtn = true;
					this.btnName = this.clockValidate(this.formData.lat,this.formData.lng);
				}else{
					this.submitBtn = false;
					this.btnName = "巡逻签到";
				}
			},
		},
		onShow() {
			console.log("onShow")
			this.setLoaction();
			this.mapTimer = setInterval(this.setLoaction,5000);
			this.dateTimer = setInterval(this.dateInterval,1000);
			this.initClockPoint();
		},
		onReady() {
			this.aqffMap = uni.createMapContext("aqffMap",this);
			console.log(this.aqffMap);
		},
		destroyed(){
			console.log("destory");
			clearInterval(this.mapTimer);
			clearInterval(this.dateTimer);
		}
	}
</script>

<style>
	.map{
		margin-top: 25rpx;
		margin-bottom: 25rpx;
		width: 100%; 
		height: 500rpx;
	}
	.control{
		width: 50rpx;
		height: 50rpx;
		position: absolute;
		bottom: 25rpx;
		right: 25rpx;
	}
	
	.buttons{
		display: flex;
		width: 100%;
		margin-top: 20upx;
		justify-content: center;
	}
	.buttons button{
		margin: 0 50rpx;
	}
</style>
